// 流程编辑相关功能
function showProcessEditor(materials) {
    const processContainer = document.querySelector('.card-4');
    try {
        if (!window.skillpointData) {
            throw new Error('项目数据未加载');
        }

        const methods = window.skillpointData.attributes.filter(attr => attr.type === 'method');
        
        processContainer.innerHTML = `
            <div class="process-editor">
                <h3>第${window.currentStep}步</h3>
                <div class="process-section">
                    <h4>消耗材料</h4>
                    <div class="materials-list">
                        ${materials.map(material => `
                            <div class="checkbox-item">
                                <input type="checkbox" id="process_${material.varName}" value="${material.varName}"
                                       data-name="${material.name}" data-step="${material.step || 1}"
                                       data-unit="${material.unit || ''}"
                                       onchange="updateRecipe(window.currentMaterials)">
                                <label for="process_${material.varName}">${material.name}</label>
                            </div>
                        `).join('')}
                    </div>
                </div>
                <div class="process-section">
                    <h4>使用方法</h4>
                    <div class="methods-list">
                        ${methods.map(method => `
                            <div class="checkbox-item">
                                <input type="checkbox" id="method_${method.varName}" value="${method.varName}"
                                       data-name="${method.name}"
                                       onchange="updateRecipe(window.currentMaterials)">
                                <label for="method_${method.varName}">${method.name}</label>
                            </div>
                        `).join('')}
                    </div>
                </div>
                <div class="process-section">
                    <h4>产出材料</h4>
                    <div class="products-list">
                        ${materials.map(material => `
                            <div class="checkbox-item">
                                <input type="checkbox" id="product_${material.varName}" value="${material.varName}"
                                       data-name="${material.name}" data-step="${material.step || 1}"
                                       data-unit="${material.unit || ''}"
                                       onchange="updateRecipe(window.currentMaterials)">
                                <label for="product_${material.varName}">${material.name}</label>
                            </div>
                        `).join('')}
                    </div>
                </div>
                <div class="process-section">
                    <h4>步骤描述</h4>
                    <textarea id="stepDescription" placeholder="请描述这一步骤的具体操作..."></textarea>
                </div>
                <div class="process-actions">
                    <button class="prev-btn" onclick="handlePrevStep()">返回</button>
                    <button class="next-btn" onclick="handleNextStep()">下一步</button>
                    <button class="complete-btn" onclick="saveProject()">完成</button>
                </div>
            </div>
        `;

        // 绑定复选框变化事件
        document.querySelectorAll('.process-editor input[type="checkbox"]').forEach(checkbox => {
            checkbox.onchange = () => updateRecipe(window.currentMaterials);
        });

        // 显示初始配方
        updateRecipe(window.currentMaterials);

    } catch (error) {
        console.error('Error showing process editor:', error);
        processContainer.innerHTML = '加载流程编辑器失败: ' + error.message;
    }
}

window.updateRecipe = function() {
    const recipeContainer = document.querySelector('.pink-card');
    const consumedMaterials = Array.from(document.querySelectorAll('input[id^="process_"]:checked'))
        .map(input => ({
            varName: input.value,
            name: input.dataset.name,
            amount: parseInt(input.dataset.amount || input.dataset.step),
            step: parseInt(input.dataset.step),
            unit: input.dataset.unit
        }));

    const usedMethods = Array.from(document.querySelectorAll('input[id^="method_"]:checked'))
        .map(input => ({
            varName: input.value,
            name: input.dataset.name
        }));

    const producedMaterials = Array.from(document.querySelectorAll('input[id^="product_"]:checked'))
        .map(input => ({
            varName: input.value,
            name: input.dataset.name,
            amount: parseInt(input.dataset.amount || input.dataset.step),
            step: parseInt(input.dataset.step),
            unit: input.dataset.unit
        }));

    recipeContainer.innerHTML = `
        <div class="recipe-container">
            <div class="recipe-left">
                <div class="section-title">消耗材料</div>
                <div class="consumed-materials">
                    ${consumedMaterials.map(material => `
                        <div class="recipe-item" data-varname="${material.varName}">
                            <span class="recipe-name">${material.name}</span>
                            <div class="recipe-amount-wrapper">
                                <button class="amount-btn plus" onclick="adjustAmount('${material.varName}', 1, ${material.step}, true)">+</button>
                                <span class="recipe-amount">${material.amount}${material.unit}</span>
                                <button class="amount-btn minus" onclick="adjustAmount('${material.varName}', -1, ${material.step}, true)">-</button>
                            </div>
                        </div>
                    `).join('')}
                </div>
                <div class="section-title">使用方法</div>
                <div class="recipe-methods">
                    ${usedMethods.map(method => `
                        <div class="recipe-item" data-varname="${method.varName}">
                            <span class="recipe-name">${method.name}</span>
                            <button class="remove-btn" onclick="removeMethod('${method.varName}')">×</button>
                        </div>
                    `).join('')}
                </div>
            </div>
            <div class="recipe-right">
                <div class="section-title">产出材料</div>
                <div class="produced-materials">
                    ${producedMaterials.map(material => `
                        <div class="recipe-item" data-varname="${material.varName}">
                            <span class="recipe-name">${material.name}</span>
                            <div class="recipe-amount-wrapper">
                                <button class="amount-btn plus" onclick="adjustAmount('${material.varName}', 1, ${material.step}, false)">+</button>
                                <span class="recipe-amount">${material.amount}${material.unit}</span>
                                <button class="amount-btn minus" onclick="adjustAmount('${material.varName}', -1, ${material.step}, false)">-</button>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
    `;

    // 更新步骤描述
    const description = document.getElementById('stepDescription');
    if (description) {
        const consumedText = consumedMaterials.map(m => `${m.amount}${m.unit}${m.name}`).join('、');
        const methodsText = usedMethods.map(m => m.name).join('、');
        const producedText = producedMaterials.map(m => `${m.amount}${m.unit}${m.name}`).join('、');

        let text = '';
        if (consumedText) text += `使用${consumedText}`;
        if (methodsText) text += `，通过${methodsText}`;
        if (producedText) text += `，生产出${producedText}`;

        description.value = text || '';
    }
};

function generateMaterialsList(materials, prefix, isConsumed) {
    return Array.from(document.querySelectorAll(`.process-editor input[type="checkbox"][id^="${prefix}"]:checked`))
        .map(cb => materials.find(m => m.varName === cb.value))
        .filter(Boolean)
        .map(material => {
            const amount = material.currentAmount || material.step || 1;
            return `
                <div class="recipe-item" data-varname="${material.varName}">
                    <span class="recipe-name">${material.name}</span>
                    <div class="recipe-amount-wrapper">
                        <span class="recipe-amount">${amount}${material.unit || ''}</span>
                        <button class="amount-btn plus" onclick="adjustAmount('${material.varName}', 1, ${material.step || 1}, ${isConsumed})">+</button>
                        <button class="amount-btn minus" onclick="adjustAmount('${material.varName}', -1, ${material.step || 1}, ${isConsumed})">-</button>
                    </div>
                </div>
            `;
        })
        .join('');
}

function generateMethodsList() {
    const skillpointPath = document.querySelector('#saveProject')?.getAttribute('data-filepath');
    return Array.from(document.querySelectorAll('.process-editor input[type="checkbox"][id^="method_"]:checked'))
        .map(cb => {
            const method = loadMethodsList(skillpointPath).find(m => m.varName === cb.value);
            return method ? `
                <div class="recipe-method">
                    <span class="method-name">📖 ${method.name}</span>
                    <button class="remove-method" onclick="removeMethod('${method.varName}')">×</button>
                </div>
            ` : '';
        })
        .join('');
}

function loadMethodsList(skillpointPath) {
    if (!skillpointPath) return [];
    try {
        const skillpointData = JSON.parse(fs.readFileSync(skillpointPath, 'utf8'));
        return skillpointData.attributes.filter(attr => attr.type === 'method');
    } catch (error) {
        console.error('Error loading methods list:', error);
        return [];
    }
}

function adjustAmount(varName, delta, step, isConsumed) {
    const container = isConsumed ? '.consumed-materials' : '.produced-materials';
    const item = document.querySelector(`${container} .recipe-item[data-varname="${varName}"]`);
    const amountSpan = item.querySelector('.recipe-amount');
    const material = window.currentMaterials.find(m => m.varName === varName);
    
    let currentAmount = parseFloat(amountSpan.textContent) || 0;
    currentAmount += (delta * step);

    if (currentAmount <= 0) {
        document.getElementById(`${isConsumed ? 'process' : 'product'}_${varName}`).checked = false;
        updateRecipe(window.currentMaterials);
    } else {
        material.currentAmount = currentAmount;
        amountSpan.textContent = `${currentAmount}${material.unit || ''}`;
        // 更新步骤描述
        const description = generateStepDescription();
        const descriptionArea = document.getElementById('stepDescription');
        if (descriptionArea) {
            descriptionArea.value = description;
        }
    }
}

function generateStepDescription() {
    let parts = [];
    
    // 材料消耗
    const consumedMaterials = Array.from(document.querySelectorAll('.consumed-materials .recipe-item'))
        .map(item => {
            const name = item.querySelector('.recipe-name').textContent;
            const amount = item.querySelector('.recipe-amount').textContent;
            return `${amount}${name}`;
        });
    if (consumedMaterials.length > 0) {
        parts.push('消耗' + consumedMaterials.join('、'));
    }
    
    // 使用方法
    const methods = Array.from(document.querySelectorAll('.methods-selection input:checked'))
        .map(cb => cb.nextElementSibling.textContent);
    if (methods.length > 0) {
        parts.push('通过' + methods.join('、'));
    }
    
    // 产出材料
    const products = Array.from(document.querySelectorAll('.produced-materials .recipe-item'))
        .map(item => {
            const name = item.querySelector('.recipe-name').textContent;
            const amount = item.querySelector('.recipe-amount').textContent;
            return `${amount}${name}`;
        });
    if (products.length > 0) {
        parts.push('得到' + products.join('、'));
    }
    
    // 能力变化
    const abilityChanges = Array.from(document.querySelectorAll('.ability-changes .ability-change-item'))
        .map(item => {
            const name = item.querySelector('.ability-name').textContent;
            const value = parseFloat(item.querySelector('input').value);
            const changeText = value > 0 ? '提升' : '降低';
            return `<span class="ability-text">${name}${changeText}${Math.abs(value)}</span>`;
        });
    if (abilityChanges.length > 0) {
        parts.push(abilityChanges.join('，'));
    }
    
    return parts.join('，');
}

function saveCurrentStep() {
    const stepData = {
        stepNumber: window.currentStep,
        description: document.getElementById('stepDescription').value,
        materials: Array.from(document.querySelectorAll('.consumed-materials .recipe-item'))
            .map(item => ({
                name: item.querySelector('.recipe-name').textContent,
                amount: item.querySelector('.recipe-amount').textContent,
                varName: item.dataset.varname
            })),
        products: Array.from(document.querySelectorAll('.produced-materials .recipe-item'))
            .map(item => ({
                name: item.querySelector('.recipe-name').textContent,
                amount: item.querySelector('.recipe-amount').textContent,
                varName: item.dataset.varname
            })),
        methods: Array.from(document.querySelectorAll('.methods-selection input:checked'))
            .map(cb => ({
                name: cb.nextElementSibling.textContent,
                varName: cb.value
            }))
    };
    
    window.processSteps.push(stepData);
}

function completeStep() {
    saveCurrentStep();
    showProjectForm(document.querySelector('#saveProject').getAttribute('data-filepath'));
}

function nextStep() {
    saveCurrentStep();
    window.currentStep++;
    showProcessEditor(window.currentMaterials);
}

// 恢复 removeMethod 函数
window.removeMethod = function(varName) {
    const checkbox = document.getElementById(`method_${varName}`);
    if (checkbox) {
        checkbox.checked = false;
        updateRecipe();
    }
};

// 修改导出
module.exports = {
    showProcessEditor,
    updateRecipe,
    completeStep,
    nextStep,
    adjustAmount,
    removeMethod,  // 重新添加到导出
    generateStepDescription
};

// 添加样式
const style = document.createElement('style');
style.textContent = `
    .recipe-methods .recipe-item {
        position: relative;
        padding-right: 20px;
    }

    .recipe-methods .remove-btn {
        position: absolute;
        right: -8px;
        top: -8px;
        width: 16px;
        height: 16px;
        line-height: 14px;
        text-align: center;
        border-radius: 50%;
        border: none;
        background-color: #ff4444;
        color: white;
        cursor: pointer;
        font-size: 12px;
        opacity: 0.7;
    }

    .recipe-methods .remove-btn:hover {
        opacity: 1;
    }
`;
document.head.appendChild(style); 